package com.ogawa.chair7808.manager

import android.content.Context
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import com.example.reslib.Constants
import com.example.reslib.utils.PreferenceWrapper
import com.jeremyliao.liveeventbus.LiveEventBus
import com.ogawa.base.Constant.CommmandNum
import com.ogawa.base.Constant.Constant.LIVE_EVENT_BUS_KEY_END_TIME
import com.ogawa.base.Constant.Constant.LIVE_EVENT_BUS_KEY_UPDATE_TIME
import com.ogawa.base.callback.GetOnlineCallback
import com.ogawa.base.mqtt.MqttManager
import com.ogawa.base.network.BaseResponse
import com.ogawa.base.network.RetrofitManager
import com.ogawa.base.network.bean.BeanOnline
import com.ogawa.base.network.bean.BeanUpdata
import com.ogawa.base.utils.DownTimer
import com.ogawa.base.utils.StringUtils
import com.ogawa.base.utils.StringUtils.nullStrToEmpty
import com.ogawa.chair7808.bean.Device7808StateBean
import com.ogawa.chair7808.bean.Massage7808Armchair
import com.ogawa.chair7808.bean.TempDevice7808StateBean
import rx.Subscriber
import java.io.File
import java.io.IOException

class DataManager private constructor() {
    var isMqttConnect //mqtt是否连接成功
            = false
    private var mSn //序列号="OGA75061812010001"
            : String? = null
    var isInitSucceed = false
    var isConnectSocket //是否连接上了socket
            = false
    private val hasCheckUpdataOk = false
    var isNetCanUse = false
    private var mUpdataBean: BeanUpdata? = null
    var lastAutoProgram = 0
    var isHandOutMessageActivity //是否是自己退出按摩程序
            = false
    private var mTimer: DownTimer? = null
    private var deviceStatusBean = Device7808StateBean()
    fun getDevice7808StateBean():Device7808StateBean{
        return deviceStatusBean
    }
    fun getmUpdataBean(): BeanUpdata? {
        return mUpdataBean
    }

    fun setmUpdataBean(mUpdataBean: BeanUpdata?) {
        this.mUpdataBean = mUpdataBean
    }

    fun getmSn(): String? {
        return mSn
    }

    fun setmSn(mSn: String?) {
        this.mSn = mSn
    }

    /**
     * 获取是否在线
     *
     * @param params 设备序号或mac地址
     * @param isMac  是否查询mac 0否 1是
     */
    fun getOnline(context: Context?, params: String, isMac: Int, callback: GetOnlineCallback?) {
        if (callback == null) {
            return
        }
        val retrofitManager = RetrofitManager.getInstance()
        retrofitManager.setUri(Constants.URI_ONLINE + "?param=" + params + "&isMac=" + isMac)
        retrofitManager.setMethod(Constants.HTTP_GET)
        retrofitManager.setJsonBody(null)
        retrofitManager.getOnlineEvent(params, isMac, object : Subscriber<BaseResponse<BeanOnline?>?>() {
            override fun onCompleted() {}
            override fun onError(e: Throwable) {
                Log.e("onError", e.toString() + "")
                callback.onGetOnlineFailure()
            }

            override fun onNext(program: BaseResponse<BeanOnline?>?) {
                Log.e("fhb", "GETONLINE --- 成功 ---= $program")
                if (program?.errCode == "0" && !TextUtils.isEmpty(program.data?.sn)) {
                    val mSp = PreferenceWrapper()
                    mSp.setStringValueAndCommit(com.ogawa.base.Constant.Constants.SN, program.data?.sn)
                    inst!!.setmSn(program.data?.sn)
                    callback.onGetOnlineSuccess(program)
                } else {
                    callback.onGetOnlineFailure()
                }
            }

        })
    }

    fun sendCommond(code: String?): Boolean {
        MqttManager.getInstance().publish(code, "")
        return true
    }

    fun sendCommond(code: String?, model: String?): Boolean {
        MqttManager.getInstance().publish(code, model)
        when (code) {
            CommmandNum.TIME_5 -> {
                when (model) {
                    com.ogawa.base.Constant.Constants.TIME_5 -> {
                        inst!!.setTime(5, 0)
                    }
                    com.ogawa.base.Constant.Constants.TIME_10 -> {
                        inst!!.setTime(10, 0)
                    }
                    com.ogawa.base.Constant.Constants.TIME_15 -> {
                        inst!!.setTime(15, 0)
                    }
                    com.ogawa.base.Constant.Constants.TIME_20 -> {
                        inst!!.setTime(20, 0)
                    }
                    com.ogawa.base.Constant.Constants.TIME_25 -> {
                        inst!!.setTime(25, 0)
                    }
                    com.ogawa.base.Constant.Constants.TIME_30 -> {
                        inst!!.setTime(30, 0)
                    }
                }
            }
        }
        return true
    }

    /**
     * 是否有开机
     *
     * @return
     */
    val isOpen: Boolean
        get() {
            var ret = false
            try {
                ret = "1" == deviceStatusBean.runningStatus
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ret
        }

    //是否有手动程序在按摩
    val isHandProgram:Boolean
        get(){
            var ret = false
            try {
                val iskneadAndKnock = StringUtils.getValue(deviceStatusBean.kneadAndKnock) > 0
                val ishandProgram = StringUtils.getValue(deviceStatusBean.handProgram) > 0
                val istuinaStatus = StringUtils.getValue(deviceStatusBean.tuinaStatus) > 0
                val iskneadStatus = StringUtils.getValue(deviceStatusBean.kneadStatus) > 0
                val isswedishStatus = StringUtils.getValue(deviceStatusBean.swedishStatus) > 0
                val isknockStatus = StringUtils.getValue(deviceStatusBean.knockStatus) > 0
                val isshiasuStatus = StringUtils.getValue(deviceStatusBean.shiasuStatus) > 0
                val iskneadAndKnockStatus = StringUtils.getValue(deviceStatusBean.kneadAndKnockStatus) > 0
                val isflapStatus = StringUtils.getValue(deviceStatusBean.flapStatus) > 0
                if (iskneadAndKnock || ishandProgram || istuinaStatus || iskneadStatus
                        || isswedishStatus || isknockStatus
                        || isshiasuStatus || iskneadAndKnockStatus
                        || isflapStatus) {
                    ret = true
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ret
        }
    /**
     * 是否有程序运行
     *
     * @return
     */
    val isRunning: Boolean
        get() {
            var ret = false
            try {
                val isautoProgram = StringUtils.getValue(deviceStatusBean.autoProgram) > 0
                if (isHandProgram || isautoProgram) {
                    ret = true
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ret
        }




    fun pauseTime() {
        if (mTimer != null) {
            mTimer!!.pause()
        }
    }

    fun reStarTime() {
        if (mTimer != null) {
            mTimer!!.resume()
        }
    }

    fun cancelTime() {
        if (mTimer != null) {
            mTimer!!.cancel()
        }
    }

    fun setTime(min: Int, sec: Int) {
        cancelTime()
        mTimer = DownTimer() //实例化
        mTimer!!.totalTime = (min * 60 * 1000 + sec * 1000).toLong() //设置毫秒数
        mTimer!!.intervalTime = 1000 //设置间隔数
        mTimer!!.setTimerLiener(object : DownTimer.TimeListener {
            override fun onFinish() {
                LiveEventBus.get(LIVE_EVENT_BUS_KEY_END_TIME).post(0)
            }

            override fun onInterval(time: Long) {
                val showTime = time / 1000
                val timeBean = TimeBean(showTime / 60, showTime % 60)
                LiveEventBus.get(LIVE_EVENT_BUS_KEY_UPDATE_TIME).post(timeBean)
            }
        })
        mTimer!!.start()
    }

    fun analysisDeviceStatusBean(functions: TempDevice7808StateBean.FunctionsBean) {
        deviceStatusBean.timeRemaining = nullStrToEmpty(functions.timeRemaining.modelValue)
        deviceStatusBean.runningStatusQuery = nullStrToEmpty(functions.runningStatusQuery.modelValue)
        deviceStatusBean.runningStatus = nullStrToEmpty(functions.runningStatus.modelValue)
        deviceStatusBean.timeExpired = nullStrToEmpty(functions.timeExpired.modelValue)
        deviceStatusBean.waringTone = nullStrToEmpty(functions.waringTone.modelValue)
        deviceStatusBean.resetSucccessFlag = nullStrToEmpty(functions.resetSucccessFlag.modelValue)
        deviceStatusBean.wifiName = nullStrToEmpty(functions.wifiName.modelValue)
        deviceStatusBean.wifiSignal = nullStrToEmpty(functions.wifiSignal.modelValue)
        deviceStatusBean.wifiWay = nullStrToEmpty(functions.wifiWay.modelValue)
        deviceStatusBean.wifiEnctyption = nullStrToEmpty(functions.wifiEnctyption.modelValue)
        deviceStatusBean.knead = nullStrToEmpty(functions.knead.modelValue)
        deviceStatusBean.swedish = nullStrToEmpty(functions.swedish.modelValue)
        deviceStatusBean.knock = nullStrToEmpty(functions.knock.modelValue)
        deviceStatusBean.shiasu = nullStrToEmpty(functions.shiasu.modelValue)
        deviceStatusBean.flap = nullStrToEmpty(functions.flap.modelValue)
        deviceStatusBean.tuina = nullStrToEmpty(functions.tuina.modelValue)
        deviceStatusBean.kneadAndKnock = nullStrToEmpty(functions.kneadAndKnock.modelValue)
        deviceStatusBean.handProgram = nullStrToEmpty(functions.handProgram.modelValue)
        deviceStatusBean.tuinaStatus = nullStrToEmpty(functions.tuinaStatus.modelValue)
        deviceStatusBean.kneadStatus = nullStrToEmpty(functions.kneadStatus.modelValue)
        deviceStatusBean.swedishStatus = nullStrToEmpty(functions.swedishStatus.modelValue)
        deviceStatusBean.knockStatus = nullStrToEmpty(functions.knockStatus.modelValue)
        deviceStatusBean.shiasuStatus = nullStrToEmpty(functions.shiasuStatus.modelValue)
        deviceStatusBean.kneadAndKnockStatus = nullStrToEmpty(functions.kneadAndKnockStatus.modelValue)
        deviceStatusBean.flapStatus = nullStrToEmpty(functions.flapStatus.modelValue)
        deviceStatusBean.autoProgram = nullStrToEmpty(functions.autoProgram.modelValue)
        deviceStatusBean.xStatus = nullStrToEmpty(functions.xStatus.modelValue)
        deviceStatusBean.legPosAdjust = nullStrToEmpty(functions.legPosAdjust.modelValue)
        deviceStatusBean.legPosAdjustX = nullStrToEmpty(functions.legPosAdjustX.modelValue)
        deviceStatusBean.backPosAdjust = nullStrToEmpty(functions.backPosAdjust.modelValue)
        deviceStatusBean.zeroGravity = nullStrToEmpty(functions.zeroGravity.modelValue)
        deviceStatusBean.yStatus = nullStrToEmpty(functions.yStatus.modelValue)
        deviceStatusBean.yPos = nullStrToEmpty(functions.yPos.modelValue)
        deviceStatusBean.shoulderDetectCheck = nullStrToEmpty(functions.shoulderDetectCheck.modelValue)
        deviceStatusBean.kneadSpeed = nullStrToEmpty(functions.kneadSpeed.modelValue)
        deviceStatusBean.knockSpeed = nullStrToEmpty(functions.knockSpeed.modelValue)
        deviceStatusBean.footScrollSenior = nullStrToEmpty(functions.footScrollSenior.modelValue)
        deviceStatusBean.timeSet = nullStrToEmpty(functions.timeSet.modelValue)
        deviceStatusBean.heatFullBody = nullStrToEmpty(functions.heatFullBody.modelValue)
        deviceStatusBean.kneeHeat = nullStrToEmpty(functions.kneeHeat.modelValue)
        deviceStatusBean.heatWaist = nullStrToEmpty(functions.heatWaist.modelValue)
        deviceStatusBean.footWheelButton = nullStrToEmpty(functions.footWheelButton.modelValue)
        deviceStatusBean.led = nullStrToEmpty(functions.led.modelValue)
        deviceStatusBean.antiPinchCheck = nullStrToEmpty(functions.antiPinchCheck.modelValue)
        deviceStatusBean.footWheelIcon = nullStrToEmpty(functions.footWheelIcon.modelValue)
        deviceStatusBean.ledIcon = nullStrToEmpty(functions.ledIcon.modelValue)
        deviceStatusBean.heatLevelRank = nullStrToEmpty(functions.heatLevelRank.modelValue)
        deviceStatusBean.airIntensityAdjust = nullStrToEmpty(functions.airIntensityAdjust.modelValue)
        deviceStatusBean.xPos = nullStrToEmpty(functions.xPos.modelValue)
        deviceStatusBean.massageStrength = nullStrToEmpty(functions.massageStrength.modelValue)
        deviceStatusBean.massageSpeed = nullStrToEmpty(functions.massageSpeed.modelValue)
        deviceStatusBean.airIntensity = nullStrToEmpty(functions.airIntensity.modelValue)
        deviceStatusBean.airCellShoulder = nullStrToEmpty(functions.airCellShoulder.modelValue)
        deviceStatusBean.airCellHip = nullStrToEmpty(functions.airCellHip.modelValue)
        deviceStatusBean.airCellHand = nullStrToEmpty(functions.airCellHand.modelValue)
        deviceStatusBean.airCellleg = nullStrToEmpty(functions.airCellleg.modelValue)
        deviceStatusBean.airCellFootSide = nullStrToEmpty(functions.airCellFootSide.modelValue)
        deviceStatusBean.airCellWholebody = nullStrToEmpty(functions.airCellWholebody.modelValue)
        deviceStatusBean.airCellFootStatus = nullStrToEmpty(functions.airCellFootStatus.modelValue)
        deviceStatusBean.airCelllegStatus = nullStrToEmpty(functions.airCelllegStatus.modelValue)
        deviceStatusBean.airCellHandStatus = nullStrToEmpty(functions.airCellHandStatus.modelValue)
        deviceStatusBean.airCellSeatStatus = nullStrToEmpty(functions.airCellSeatStatus.modelValue)
        deviceStatusBean.airCellShoulderStatus = nullStrToEmpty(functions.airCellShoulderStatus.modelValue)
        deviceStatusBean._3DPosIconBean = nullStrToEmpty(functions.`_$3DPosIcon`.functionCode)
        deviceStatusBean._4d = nullStrToEmpty(functions.`_$4D`.functionCode)
    }




    companion object {
        private  var mInst: DataManager ?= null
        private val mLock = Any()
        @JvmStatic
        val inst: DataManager
            get() {
                if (mInst == null) {
                    synchronized(mLock) { mInst = DataManager() }
                }
                return mInst!!
            }
        /**
         * 日志。。。。
         */
        /**
         * 创建文件或文件夹
         *
         * @param fileName 文件名或问文件夹名
         */
        fun createFile(fileName: String): File {
            val file = File(sDCardPath + fileName)
            println("创建了文件夹" + sDCardPath + fileName)
            if (fileName.indexOf(".") != -1) {
                // 说明包含，即使创建文件, 返回值为-1就说明不包含.,即使文件
                try {
                    file.createNewFile()
                } catch (e: IOException) {
                    // TODO Auto-generated catch block
                    e.printStackTrace()
                }
                println("创建了文件")
            } else {
                // 创建文件夹
                file.mkdir()
                println("创建了文件夹")
            }
            return file
        }

        private var SDPATH = ""
        fun creatFile(): File {
            return createFile("Log7506")
        }
        //   public static void setLog(String commond){
        //       Logger.file(LogTag.mk("sendCommond"), "sendCommond.txt", dir, new NullPointerException(), commond);
        //   }
        /**
         * 获取到sd卡的根目录，并以String形式返回
         *
         * @return
         */
        val sDCardPath: String
            get() {
                SDPATH = Environment.getExternalStorageDirectory().toString() + "/"
                return SDPATH
            }
    }
}